import Config from './config.js'
import store from '../store'
 // #ifdef APP-PLUS
 // 计时器参数
    let imter = null;
    // #endif
export default async function request (opt) {
    // #ifdef APP-PLUS
    // 防抖功能 进入页面后执行的onload和onshow里接口调用好几个的话就会一直重复执行 加入防抖后只让连续执行的最后一次执行这个判断网络的事件
    let networkType = ''
    // 不是null先销毁定时器
    if(imter!=null){
      clearTimeout(imter)
    }
    // 定时器赋值 执行定时器
    imter = setTimeout(()=>{
       const pages = getCurrentPages() //当前页面栈
       // configRoue有这个值时就不让执行下面的判断是否有网
      if(uni.getStorageSync('configRoue')){
        // 删除本地缓存configRoue 让进入页面后的事件调用接口来判断是否有网
        uni.removeStorageSync('configRoue')
      }else{
        // 接口请求时 判断是否有网络
        uni.getNetworkType({
            success: (res) => {
              // res.networkType 为none时说明没有网络
            if(res.networkType == 'none'){
              // 变量赋值
              networkType = res.networkType
              // 关闭提示
                uni.hideLoading();
                // 删除刷新标识
                uni.removeStorageSync('netNetworkFlag')
                // 进入无网络页面
                uni.navigateTo({
                  url:'/standard/netNetwork/netNetwork'
                })
            }
          },
        })     
      }
      clearTimeout(imter)
    },1000)
    // 没有网时就不执行下面的内容
    if(networkType=='none'){
      return false
    }
    // #endif
    opt = opt || {};
    opt.url = opt.url || '';
    opt.data = opt.data || null;
    opt.method = opt.method || 'GET';
	
	let otherParam = {};
	if(!opt.responseType){
		opt.header = opt.header || {
		    "Content-Type": "application/x-www-form-urlencoded",
			"Language": Config.curLang
		};
		otherParam.dataType = 'json'
	}else{
		opt.header = {
			"Language": Config.curLang
		}
		otherParam.responseType = opt.responseType;
		if(opt.dataType){
			otherParam.dataType = opt.dataType
		}
	}
	
	let userInfo = uni.getStorageSync('userInfo') || '';

	if(opt.url.indexOf('frontLogin/oauth/token')>-1||opt.url.indexOf('v3/video/front/video/setting/getSettingList')>-1){
	    opt.header.Authorization = 'Basic VVcxS2FsSnVTblppYmxFOTpVMjFHTWxsVlFrUmlNMEkxVlcxc2JtRklVa0ZWTW5oMldrYzVkUT09';
	  }else {
		let token = '';
		if(userInfo&&userInfo.access_token){
			token = userInfo.access_token;
		}
	    opt.header.Authorization = 'Bearer '+token;
		
		//判断时间
		let cur_time = new Date().getTime();
		let start_time = uni.getStorageSync('sld_login_time');
		let sld_refresh_token = userInfo.refresh_token;
		if(start_time && (cur_time - start_time > ( 58 * 60 * 1000)) && sld_refresh_token){
		    //用户token过期之后重新根据refresh_token获取token(58分钟，token的有效期是60分钟)
		    let res = await refreshToken(sld_refresh_token);
			res = res.data!=undefined?res.data:{state:255}
		    if (res.state == 200) {
				   uni.setStorageSync('sld_token', res.data.access_token)
				    uni.setStorageSync('sld_refresh_token', res.data.refresh_token)
				   let curUserInfo = store.state.userInfo;
				   curUserInfo.access_token = res.data.access_token;
				   curUserInfo.refresh_token = res.data.refresh_token;
				   store.commit('login',curUserInfo)
		      //更新sld_token的时间
		      uni.setStorage({
		          key: 'sld_login_time',
		          data: new Date().getTime(),
		      });
			  opt.header.Authorization = 'Bearer '+ curUserInfo.access_token;
		    } else {
		      //清空本地用户信息
				   store.commit('logout','')
		    }
		  }
	  }
	  
	return new Promise((resolve,reject)=>{
		uni.request({
		    url: Config.apiUrl + opt.url,
		    data: opt.data,
		    method: opt.method,
		    header: opt.header,
		    ...otherParam,
		    success: res=>{
				if(res.data.state==266){
					store.commit('logout','')
				}else{
					resolve(res.data);
				}
		  },
		   fail: err=>{
			reject(err);
		  },
			complete: (res)=>{
			}
		})
  })
    
}

/** 
 * 刷新token
 * @zjf-2021-07-22
 */
function refreshToken(refresh_token) {
	return new Promise(func => {
		uni.request({
		    url: Config.apiUrl + 'v3/frontLogin/oauth/token',
		    data: {
					grant_type: 'refresh_token',
					refresh_token: refresh_token,
				},
		    method: 'POST',
		    header: {
			    "Content-Type": "application/x-www-form-urlencoded",
				"Language": Config.curLang,
				Authorization: 'Basic VVcxS2FsSnVTblppYmxFOTpVMjFHTWxsVlFrUmlNMEkxVlcxc2JtRklVa0ZWTW5oMldrYzVkUT09',
			},
		    success: res=>{
				func(res);
		  }
		})
	})
}